/**
 * Parse the time to string
 * @param {(Object|string|number)} time
 * @param {string} cFormat
 * @returns {string | null}
 */
export function parseTime(time, cFormat) {
  if (arguments.length === 0) {
    return null
  }
  const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
  // console.log(format)
  let date
  // console.log(typeof time)
  // console.log(time)
  if (typeof time === 'object') {
    date = time
  } else {
    if ((typeof time === 'string') && (/^[0-9]+$/.test(time))) {
      time = parseInt(time)
    }
    if ((typeof time === 'number') && (time.toString().length === 10)) {
      time = time * 1000
    }
    date = new Date(time)
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  const time_str = format.replace(/{([ymdhisa])+}/g, (result, key) => {
    const value = formatObj[key]
    // Note: getDay() returns 0 on Sunday
    if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value] }
    return value.toString().padStart(2, '0')
  })
  return time_str
}

/**
 * @param {number} time
 * @param {string} option
 * @returns {string}
 */
export function formatTime(time, option) {
  if (('' + time).length === 10) {
    time = parseInt(time) * 1000
  } else {
    time = +time
  }
  const d = new Date(time)
  const now = Date.now()
  const diff = (now - d) / 1000
  if (diff < 30) {
    return '刚刚'
  } else if (diff < 3600) {
    // less 1 hour
    return Math.ceil(diff / 60) + '分钟前'
  } else if (diff < 3600 * 24) {
    return Math.ceil(diff / 3600) + '小时前'
  } else if (diff < 3600 * 24 * 2) {
    return '1天前'
  }
  if (option) {
    return parseTime(time, option)
  } else {
    return (
      d.getMonth() +
      1 +
      '月' +
      d.getDate() +
      '日' +
      d.getHours() +
      '时' +
      d.getMinutes() +
      '分'
    )
  }
}

/**
 * @param {(Object|string|number)} time
 * @returns {string | ''}
 */
export function parseDate(time) {
  if (arguments.length === 0) {
    return ''
  }
  const days = ['日', '一', '二', '三', '四', '五', '六']
  let d
  if (typeof time === 'object') {
    d = time
  } else {
    if ((typeof time === 'string') && (/^[0-9]+$/.test(time))) {
      time = parseInt(time)
    }
    if ((typeof time === 'number') && (time.toString().length === 10)) {
      time = time * 1000
    }
    d = new Date(time)
  }
  return (
    d.getMonth() +
    1 +
    '月' +
    d.getDate() +
    '日' +
    '&nbsp;&nbsp;&nbsp;&nbsp;' +
    '星期' +
    days[d.getDay()]
  )
}

/**
 * @param {string} url
 * @returns {Object}
 */
export function param2Obj(url) {
  const search = url.split('?')[1]
  if (!search) {
    return {}
  }
  return JSON.parse(
    '{"' +
    decodeURIComponent(search)
      .replace(/"/g, '\\"')
      .replace(/&/g, '","')
      .replace(/=/g, '":"')
      .replace(/\+/g, ' ') +
    '"}'
  )
}

// eslint-disable-next-line no-extend-native
Date.prototype.Format = function(fmt) { // author: meizz
  var o = {
    'M+': this.getMonth() + 1, // 月份
    'd+': this.getDate(), // 日
    'h+': this.getHours(), // 小时
    'm+': this.getMinutes(), // 分
    's+': this.getSeconds(), // 秒
    'q+': Math.floor((this.getMonth() + 3) / 3), // 季度
    'S': this.getMilliseconds() // 毫秒
  }
  if (/(y+)/.test(fmt)) {
    fmt = fmt.replace(RegExp.$1, (this.getFullYear() + '').substr(4 - RegExp.$1.length))
  }
  for (var k in o) {
    if (new RegExp('(' + k + ')').test(fmt)) {
      fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length)))
    }
  }
  return fmt
}

export function weekGetDate(year, weeks) {
  const date = new Date(year, '0', '1')
  let time = date.getTime() // 获取当前星期几,0:星期一
  const _week = date.getDay() // 当这一年的1月1日为周日时则本年有54周,否则没有54周,没有则去除第54周的提示
  if (_week !== 0) { // 一年53周情况
    if (weeks === 54) {
      return '今年没有54周'
    }
    let cnt = 0// 获取距离周末的天数
    if (_week === 0) {
      cnt = 7
    } else if (_week === 1) {
      cnt = 6
    } else if (_week === 2) {
      cnt = 5
    } else if (_week === 3) {
      cnt = 4
    } else if (_week === 4) {
      cnt = 3
    } else if (_week === 5) {
      cnt = 2
    } else if (_week === 6) {
      cnt = 1
    }
    // cnt += 1 // 加1表示以星期一为一周的第一天    // 将这个长整形时间加上第N周的时间偏移
    time += cnt * 24 * 3600000 // 第2周开始时间
    const nextYear = new Date(parseInt(year, 10) + 1, '0', '1')
    const nextWeek = nextYear.getDay()
    let lastcnt = 0 // 获取最后一周开始时间到周末的天数
    if (nextWeek === 0) {
      lastcnt = 6
    } else if (nextWeek === 1) {
      lastcnt = 0
    } else if (nextWeek === 2) {
      lastcnt = 1
    } else if (nextWeek === 3) {
      lastcnt = 2
    } else if (nextWeek === 4) {
      lastcnt = 3
    } else if (nextWeek === 5) {
      lastcnt = 4
    } else if (nextWeek === 6) {
      lastcnt = 5
    }
    if (weeks === 1) { // 第1周特殊处理    // 为日期对象 date 重新设置成时间 time
      const start = date.Format('yyyy-MM-dd')
      date.setTime(time - 24 * 3600000)
      return [start, date]
    } else if (weeks === 53) { // 第53周特殊处理
      const start = time + (weeks - 2) * 7 * 24 * 3600000 // 第53周开始时间
      const end = time + (weeks - 2) * 7 * 24 * 3600000 + lastcnt * 24 * 3600000 - 24 * 3600000 // 第53周结束时间
      date.setTime(start)
      const _start = date.Format('yyyy-MM-dd')
      date.setTime(end)
      const _end = date.Format('yyyy-MM-dd')
      return [_start, _end]
    } else {
      const start = time + (weeks - 2) * 7 * 24 * 3600000 // 第n周开始时间
      const end = time + (weeks - 1) * 7 * 24 * 3600000 - 24 * 3600000 // 第n周结束时间
      date.setTime(start)
      const _start = date.Format('yyyy-MM-dd')
      date.setTime(end)
      const _end = date.Format('yyyy-MM-dd')
      return [_start, _end]
    }
  } else { // 一年54周情况
    let cnt = 0 // 获取距离周末的天数
    if (_week === 0 && weeks === 1) { // 第一周
      cnt = 0
    } else if (_week === 0) {
      cnt = 7
    } else if (_week === 1) {
      cnt = 6
    } else if (_week === 2) {
      cnt = 5
    } else if (_week === 3) {
      cnt = 4
    } else if (_week === 4) {
      cnt = 3
    } else if (_week === 5) {
      cnt = 2
    } else if (_week === 6) {
      cnt = 1
    }
    cnt += 1 // 加1表示以星期一为一周的第一天
    // 将这个长整形时间加上第N周的时间偏移
    time += 24 * 3600000 // 第2周开始时间
    const nextYear = new Date(parseInt(year, 10) + 1, '0', '1')
    const nextWeek = nextYear.getDay()
    let lastcnt = 0 // 获取最后一周开始时间到周末的天数
    if (nextWeek === 0) {
      lastcnt = 6
    } else if (nextWeek === 1) {
      lastcnt = 0
    } else if (nextWeek === 2) {
      lastcnt = 1
    } else if (nextWeek === 3) {
      lastcnt = 2
    } else if (nextWeek === 4) {
      lastcnt = 3
    } else if (nextWeek === 5) {
      lastcnt = 4
    } else if (nextWeek === 6) {
      lastcnt = 5
    }
    if (weeks === 1) { // 第1周特殊处理
      const _start = date.Format('yyyy-MM-dd')
      date.setTime(time - 24 * 3600000)
      // alert(start + '--' + date);
      return [_start, date]
    } else if (weeks === 54) { // 第54周特殊处理
      const start = time + (weeks - 2) * 7 * 24 * 3600000 // 第54周开始时间
      const end = time + (weeks - 2) * 7 * 24 * 3600000 + lastcnt * 24 * 3600000 - 24 * 3600000 // 第53周结束时间
      date.setTime(start)
      const _start = date.Format('yyyy-MM-dd')
      date.setTime(end)
      const _end = date.Format('yyyy-MM-dd')
      return [_start, _end]
    } else {
      const start = time + (weeks - 2) * 7 * 24 * 3600000 // 第n周开始时间
      const end = time + (weeks - 1) * 7 * 24 * 3600000 - 24 * 3600000 // 第n周结束时间
      date.setTime(start)
      const _start = date.Format('yyyy-MM-dd')
      date.setTime(end)
      const _end = date.Format('yyyy-MM-dd')
      return [_start, _end]
    }
  }
}

 function isJSON_test(str) {
	if (typeof str == 'string') {
		try {
			var obj = JSON.parse(str);
			//console.log('转换成功：', obj);
			return obj;
		} catch (e) {
			//console.log('error：' + str + '!!!' + e);
			return str;
		}
	}
}
export const isJSONtest = isJSON_test
export function getLoc(locName = 'user') {
	//console.log(window.localStorage.getItem(locName))
	var loc = localStorage[locName]
	var obj =  isJSON_test(loc)
	return obj
}
export function setLoc(locName = 'user', locVal) {
	locVal = window.localStorage.setItem(locName, typeof(locVal) === 'object' ? JSON.stringify(locVal) : locVal)
}
export function removeLoc(locName = 'user') {
	return window.localStorage.removeItem(locName)
}
